package com.lkd.service.impl;


import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.lkd.constant.MessageConstant;
import com.lkd.dto.LoginDto;
import com.lkd.entity.User;
import com.lkd.exception.BusinessException;
import com.lkd.mapper.UserMapper;
import com.lkd.result.PageBean;
import com.lkd.service.RoleService;
import com.lkd.service.UserService;
import com.lkd.vo.LoginUserVo;
import com.lkd.vo.RoleVo;
import com.lkd.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleService roleService;

    //用户登录
    @Override
    public LoginUserVo login(LoginDto dto) {
        String userName = dto.getLoginName();
        String password = dto.getPassword();
        if (userName == null || "".equals(userName)) {
            throw new BusinessException(MessageConstant.USERNAME_NOT_NULL);
        }
        User user = userMapper.selectByUserName(userName);
        if (user == null) {
            throw new BusinessException(MessageConstant.ACCOUNT_NOT_FOUND);
        }
        if (!password.equals(user.getPassword())) {
            throw new BusinessException(MessageConstant.PASSWORD_ERROR);
        }
        LoginUserVo loginUserVo = new LoginUserVo();
        loginUserVo.setUserId(user.getId());
        loginUserVo.setUserName(user.getUserName());
        loginUserVo.setRoleCode(user.getRoleCode());
        loginUserVo.setRegionId(String.valueOf(user.getRegionId()));
        return loginUserVo;
    }

    @Override
    public PageBean<UserVo> findByPage(Integer pageIndex, Integer pageSize, String userName) {
        PageHelper.startPage(pageIndex, pageSize);
        List<UserVo> voList = userMapper.selectByPage(userName);
        RoleVo roleVo = roleService.selectByUserName(userName);
        for (UserVo userVo : voList) {
            userVo.setRole(roleVo);
        }
        Page page = (Page) voList;
        return new PageBean(pageIndex, pageSize, (long) page.getPages(), page.getTotal(), page.getResult());
    }

    @Override
    public List<RoleVo> findAll() {
        return roleService.selectAll();
    }

    @Override
    public void save(UserVo userVo) {
        userMapper.insert(userVo);
    }

    @Override
    public void update(UserVo userVo) {
        userMapper.updateById(userVo);
    }

    @Override
    public void delete(Integer userId) {
        userMapper.deleteById(userId);
    }

}